import thin_render from "../../../lib/thin_render.mjs";
import thin_ajax from "../../../lib/thin_ajax.mjs";
import { thin } from "../../../thin3.mjs";
import render_content from "../../../lib/render_content.mjs";
import datarover from "../../../lib/datarover.mjs";

/**
 * 渲染AJAX内容
 * @param {HTMLElement} td - 单元格元素
 * @param {Object} col - 列配置
 * @param {Object} template - 模板配置
 */
export function renderAjaxContent(td, col, template) {
  if (col.ajax?.display) {
    renderAjaxDisplay(td, col, template);
  } else if (col.ajax?.param) {
    renderAjaxParam(td, col);
  } else if (col.col) {
    thin_render(td, `[[${col.col}]]`);
  }
}

function renderAjaxDisplay(td, col, template) {
  let q = {};
  q[col.ajax.value] = datarover(td, col.col);
  thin_ajax({
    type: "get",
    url: col.ajax.url,
    data: { ...col.ajax.query, ...q },
    success: (data) => {
      if (template.debug) {
        console.log(data);
        console.log({ d: datarover(data, col.ajax.datapath) });
      }
      let d = datarover(data, col.ajax.datapath);
      if (d === undefined) {
        thin_render(td, col.col);
      } else if (Array.isArray(d) && d.length === 1) {
        thin_render(td, render_content(d[0], col.ajax.display));
      } else {
        thin_render(td, `[[${col.col}]]`);
      }
    },
  });
}

function renderAjaxParam(td, col) {
  let query = {};
  query[col.ajax.param] = datarover(td, col.col);
  thin
    .ajax({
      url: col.ajax.url,
      type: "get",
      data: { ...col.ajax.query, ...query },
    })
    .done((data) => {
      let rows = datarover(data, col.ajax.datapath);
      if (rows.length === 1) {
        thin_render(td, render_content(rows[0], col.ajax.text));
      } else {
        thin_render(td, `[[${col.col}]]`);
      }
    });
}
